import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NetEaseMusicDailyChecker {
    String account = "15038609250"; //你的网易云账号
    //String account = "18537962256"; //你的网易云账号
    String password = "327bc4e22b649d47c4546a3ec93f376b"; //MD5加密过后的密码
    String netEaseApi = ""; //
    static int apiIndex = 0;
    String uid = "";
    static NetEaseMusicDailyChecker checker = new NetEaseMusicDailyChecker();
    // 响应模型
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = null;
    // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的),同时添加上cookies
    CookieStore cookieStore = new BasicCookieStore();

    public static void main(String[] args) throws InterruptedException {
        System.out.println("每日打卡开始运行.....");
        checker.login(checker.avliableNetEaseApi());
        checker.getInfos(checker.uid);
        checker.playSongs();
    }


    /**
     * wxPusher推送到微信
     */
    public void wxPusher(){
        String appToken = "AT_A6VMHyljoiIPFNXtwWuLqOfAHZ05BF7g";  //改成自己的
        String pusherUID = "UID_uVncdmWubOe2IaqTMePcIFhAqgFn"; //改成自己的
        String text = "你要发的内容";
        //wxpusherApi
        String WxpusherURL = "http://wxpusher.zjiecode.com/api/send/message/?appToken="+appToken+"&uid="+pusherUID+"&url=http%3a%2f%2fwxpusher.zjiecode.com&content="+text;
        //httpRequest()
    }


    /**
     * 检查api是否可用
     * @return true或者false
     */
    public boolean apiCheck(String api){
        return httpRequest("get", api + "?do=check",null).getInteger("code")==301;
    }

    /**
     * 选举出一个可用的api
     * @return 可用的api
     */
    public String avliableNetEaseApi(){
        ArrayList<String> apis = new ArrayList<>();
        apis.add("https://marshy-local-rise.glitch.me/");
        apis.add("https://nebula-southern-wavelength.glitch.me/");
        apis.add("https://miao-neteasecloudmusicapi.glitch.me/");
        for (int i = apiIndex; i < apis.size(); i++) {
            if (apiCheck(apis.get(i))){
                netEaseApi = apis.get(i);
                System.out.println("api选择了:"+apis.get(i));
                return apis.get(i);
            }

       }
        System.out.println("暂无可用的网易云api!");
        return "暂无可用的网易云api!";
    }

    /**
     * 网易云账号登录
     * @param api 可用的API
     * @return 登录是否成功
     */
    public boolean login(String api){
        List<BasicNameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("uin", account));
        data.add(new BasicNameValuePair("pwd", password));

        JSONObject info = httpRequest("post", api + "?do=login", data); //发起登录账号请求


        if (info.getInteger("code")==200){ //如果登录成功
            System.out.println("用户:"+info.getJSONObject("profile").get("nickname")+"欢迎您!今天又是元气满满的一天!(￣▽￣)／");
            //登录成功后添加cookie
            BasicClientCookie cookie = new BasicClientCookie("MUSIC_U", info.getString("token"));
            uid = info.getJSONObject("profile").getString("userId");
            //放入cookiestore
            cookieStore.addCookie(cookie);
            sign();
            return true;
        }else {
            System.out.println("登陆失败o(╥﹏╥)o,返回信息:"+info);
            System.out.println("正在为您切换api....");
            login(avliableNetEaseApi());
        }
        return false;
    }

    /**
     * 每日签到
     */
    public void sign(){
        System.out.println("准备开始每日签到.....");
        ArrayList<BasicNameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("r", String.valueOf(Math.random())));
        JSONObject info = httpRequest("post", netEaseApi+"?do=sign",params);
        if(info.getInteger("code")==301){
            System.out.println("诶呀..这个api似乎挂了..╮(╯▽╰)╭ 错误信息:"+info);
            apiIndex++;
            System.out.println("正在为您切换api....");
            login(avliableNetEaseApi());
        }
        System.out.println(info.getInteger("code")==-2?"今天已经签过到辣![○･｀Д´･ ○]":"签到成功!^_^");
    }

    /**
     * 刷等级,歌曲播放量.
      * @return
     */
    public void playSongs() throws InterruptedException {
        for (int i = 1; i < 301; i++) {
            JSONObject result = httpRequest("get", netEaseApi + "?do=daka", null);
            if(result.getInteger("code")==200){
                System.out.println("成功的刷了第"+i+"首歌....返回信息:"+result);
                Thread.sleep(8000);
            }else {
                System.out.println("发生了奇怪的原因,这首歌没刷好.."+result);
            }
        }
        System.out.println("今天已经刷够了300个,明天继续加油!");
    }

    /**
     * 获取用户基本信息
     * @return
     */
    public JSONObject getInfos(String uid){
        JSONObject userInfos = httpRequest("get", netEaseApi + "?do=detail&uid="+uid, null);
        System.out.println("当前等级:"+userInfos.getString("level"));
        System.out.println("已听歌曲:"+userInfos.getString("listenSongs"));
        System.out.println("这是你来到云村的第"+userInfos.getString("createDays")+"天.");
        return userInfos;
    }


    /**
     * 发送http get请求
     * @param url 请求地址
     * @param param 携带参数
     * @return 返回响应体
     */
    public JSONObject httpRequest(String method, String url,List<BasicNameValuePair> param) {
        httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

        try {
        // 创建Http请求
        if(method.equals("get")){   // 由客户端执行(发送)Get请求
            HttpGet httpGet = new HttpGet(url);

            response = httpClient.execute(httpGet);
        }else if (method.equals("post")){ //由客户端执行(发送)post请求
            HttpPost httpPost =new HttpPost(url);
            UrlEncodedFormEntity entity= new UrlEncodedFormEntity(param,"UTF-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
        }
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                return JSON.parseObject(EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            System.out.println("网络连接超时...尝试更换下一个api!");
            apiIndex++;
            login(avliableNetEaseApi());
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }

        return new JSONObject().fluentPut("error", "程序异常!");
    }


}

